//
//  CPPactWkWebViewController.m
//  CPBaseXCode
//
//  Created by cp on 2024/9/23.
//

#import "CPPactWkWebViewController.h"
#import <WebKit/WebKit.h>
@interface CPPactWkWebViewController ()<WKScriptMessageHandler>

@property (nonatomic,strong) WKWebView *webView;
@property (nonatomic,strong) UIProgressView *myProgressView;
@property (nonatomic,assign) BOOL isFirst;
@property (nonatomic,assign) BOOL needUpdate;
/**是否已经生成报告**/
@property (nonatomic,assign) BOOL isBaoGao;
@property (nonatomic,strong) UIImage* saveImg;

@property (nonatomic,assign) BOOL havePlayer;

@end

@implementation CPPactWkWebViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.webView.frame = self.mainTwoview.bounds;
    
    if (self.havePlayer) {
        
    }else{
        
    }
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.havePlayer) {
        
    }else{
        
    }
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self removeScript];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self navAddleftIcon:@"nav_return_icon" leftStr:nil centerStr:[EmptySafe ObjectVlaue:self.titleStr] rightStr:@""];
    [self loadWebView];
    
    if (self.urlStr.length > 0) {
        [self lostNetwork:self.urlStr];
    }
}

-(void)leftOperate
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightOperate {

}

-(void)loadWebView
{
    //注册方法给h5调用
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
//    [userContentController addScriptMessageHandler:self name:@"pushCertifiedCarOwner"];
//    [userContentController addScriptMessageHandler:self name:@"getToken"];
//    [userContentController addScriptMessageHandler:self name:@"isTestEnd"];
//    [userContentController addScriptMessageHandler:self name:@"isTestBegin"];
//    [userContentController addScriptMessageHandler:self name:@"testSavePic"];
    configuration.userContentController = userContentController;
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 10.0;
    configuration.preferences = preferences;
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero
                                      configuration:configuration];
    [self.mainTwoview addSubview:self.webView];
    [self.mainTwoview addSubview:self.myProgressView];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

-(void)lostNetwork:(NSString*)urlStr
{
    NSURL *url = [NSURL URLWithString:[EmptySafe ObjectVlaue:urlStr]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

#pragma mark - 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.myProgressView.alpha = 1.0f;
        [self.myProgressView setProgress:newprogress animated:YES];
        if (newprogress >= 1.0f) {
            [UIView animateWithDuration:0.3f
                                  delay:0.3f
                                options:UIViewAnimationOptionCurveEaseOut
                             animations:^{
                self.myProgressView.alpha = 0.0f;
            }
                             completion:^(BOOL finished) {
                [self.myProgressView setProgress:0 animated:NO];
            }];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
#pragma mark - WKScriptMessageHandler
/**
 * JS 调用 OC 触发此方法
 */
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    //    100000, "认证车主"),
    //    100001, "完善个性签名"),
    //    100002, "发布动态3条"),
    //    100003, "发布一条图文动态"),
    //    100004, "点赞一条动态"),
    //    100005, "评论一条动态"),
    //    100006, "关注一位车友"),
    if ([message.name isEqualToString:@"getToken"]) {
//        NSString * jsStr = [NSString stringWithFormat:@"getTokenEvent('%@')",UserM.token];
//        [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//        }];
    }else if([message.name isEqualToString:@"isTestEnd"]){//测一测结束
        NSString *body = [NSString stringWithFormat:@"%@",message.body];
        if(body.length>0){
            _isBaoGao = YES;
            NSString *body = [NSString stringWithFormat:@"%@",message.body];

            NSURL *baseImageUrl = [NSURL URLWithString:body];
            NSData *imageData = [NSData dataWithContentsOfURL:baseImageUrl];
            UIImage *image = [UIImage imageWithData:imageData];
            self.saveImg = image;
        }
    }
    else if([message.name isEqualToString:@"isTestBegin"]){//测一测重新开始
        _isBaoGao = NO;
        NSLog(@"");
    }else if ([message.name isEqualToString:@"testSavePic"]){
        if(self.saveImg){
            //保存图片到照片库 （iOS10 以上记得在info.plist添加相册访问权限，否则可能崩溃）
            UIImageWriteToSavedPhotosAlbum(_saveImg, nil, nil, nil);
            [MBProgressHUD showSuccessMessage:@"保存成功"];
        }
    }
//#define XYLivePath @"bidachat://path?ce="
}
#pragma mark - getter and setter
- (UIProgressView *)myProgressView
{
    if (_myProgressView == nil) {
        _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 10)];
        _myProgressView.tintColor = RGBColor(89, 201, 245);
        _myProgressView.trackTintColor = [UIColor whiteColor];
    }
    return _myProgressView;
}

- (void)savePhoto
{
    UIScrollView *scroll = self.webView.subviews.firstObject;
    scroll.frame = scroll.superview.frame;
    CGRect frm = scroll.frame;
    frm.size.height = _webView.scrollView.contentSize.height;
    scroll.frame = frm;
    [scroll.superview layoutIfNeeded];
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(KScreenWidth,scroll.frame.size.height), YES, 0);
    [scroll.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef imageRef = viewImage.CGImage;
    UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRef];
    NSLog(@"sendImage==%@",sendImage);
    //保存图片到照片库 （iOS10 以上记得在info.plist添加相册访问权限，否则可能崩溃）
    UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil);
}

- (void)removeScript
{
//    [self.webView.configuration.userContentController
//     removeScriptMessageHandlerForName:@"getToken"];
//    [self.webView.configuration.userContentController
//     removeScriptMessageHandlerForName:@"pushCertifiedCarOwner"];
//    [self.webView.configuration.userContentController
//     removeScriptMessageHandlerForName:@"isTestEnd"];
//    [self.webView.configuration.userContentController
//     removeScriptMessageHandlerForName:@"isTestBegin"];
//    [self.webView.configuration.userContentController
//     removeScriptMessageHandlerForName:@"testSavePic"];
}

- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    QQNSLog(@"释放网页");
}

@end
